﻿using System;
using System.IO;
using System.Reflection;

namespace EmbeddedSharp.Core
{
    public class DefaultFunctionLoader : IFunctionLoader
    {
        protected readonly IFunctionManager FunctionManager;

        public DefaultFunctionLoader(IFunctionManager fm)
        {
            FunctionManager = fm;
        }

        public IProgressReporter ProgressReporter { get; set; }

        #region IFunctionLoader Members

        /// <summary>
        /// 
        /// </summary>
        /// <param name="location"></param>
        public void LoadFromFolder(string location)
        {
            if (!Directory.Exists(location))
            {
                throw new DirectoryNotFoundException("Cannot load functions from directory " + location);
            }

            string[] fileNames = Directory.GetFiles(location.Trim(), "*.*", SearchOption.AllDirectories);
            foreach (string fileName in fileNames)
            {
                if (fileName.EndsWith(".exe") || fileName.EndsWith(".dll"))
                {
                    try
                    {
                        Utils.Debugging("File: {0}", fileName);
                        LoadFromFile(fileName);
                    }
                    catch (Exception ex)
                    {
                        Utils.Debugging(ex.Message);
                    }
                }
            }
        }

        public static bool IsFuncNode(Type p)
        {
            if (p.FullName == "EmbeddedSharp.Core.FuncNode")
            {
                return false;
            }

            while (p != null)
            {
                if (p.FullName == "EmbeddedSharp.Core.FuncNode")
                {

                    return true;
                }

                p = p.BaseType;
            }

            return false;
        }

        public void LoadFromFile(string fileName)
        {
            try
            {
                Assembly assembly = Assembly.LoadFrom(fileName);
                Type[] types = assembly.GetTypes();

                foreach (Type type in types)
                {
                    Utils.Debugging("Loading function type: " + type.Name);
                    if (IsFuncNode(type))
                    {
                        try
                        {
                            Utils.Debugging("Loading function: " + type.Name);
                            if (ProgressReporter != null)
                            {
                                ProgressReporter.Write(type.Name);
                            }

                            int index = type.Name.IndexOf("Node");
                            string funcName = type.Name.Substring(0, index).ToLower();

                            FunctionManager.Add(funcName, type);
                            Utils.Debugging(
                                "Function '{0}' was loaded successfully.",
                                funcName);
                        }
                        catch (Exception ex)
                        {
                            Utils.Debugging(ex.Message + "\n" + ex.StackTrace);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Utils.Debugging(ex.Message + "\n" + ex.StackTrace);
                throw;
            }
        }

        #endregion

        public virtual FuncNode LoadFunction(Assembly assembly, string p)
        {
            return assembly.CreateInstance(p) as FuncNode;
        }
    }
}